import React, { useState, useEffect } from 'react';
import { Table, Button, Space, Modal, Form, Input, message, Select } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { getAssetList, createAsset, updateAsset, deleteAsset, getDepartmentList } from '../../../services/api';

const AssetList = () => {
  const [assets, setAssets] = useState([]);
  const [departments, setDepartments] = useState([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [editingAsset, setEditingAsset] = useState(null);
  const user = JSON.parse(sessionStorage.getItem('user') || '{}');

  const fetchAssets = async () => {
    setLoading(true);
    try {
      const response = await getAssetList();
      if (response.code === 200 && Array.isArray(response.data)) {
        setAssets(response.data);
      } else {
        setAssets([]);
        message.error(response.message || '获取资产列表失败');
      }
    } catch (error) {
      console.error('获取资产列表失败:', error);
      message.error('获取资产列表失败');
      setAssets([]);
    }
    setLoading(false);
  };

  const fetchDepartments = async () => {
    try {
      const response = await getDepartmentList();
      if (response.code === 200 && Array.isArray(response.data)) {
        setDepartments(response.data);
      } else {
        setDepartments([]);
        message.error(response.message || '获取部门列表失败');
      }
    } catch (error) {
      console.error('获取部门列表失败:', error);
      message.error('获取部门列表失败');
      setDepartments([]);
    }
  };

  useEffect(() => {
    fetchAssets();
    fetchDepartments();
  }, []);

  const handleAdd = () => {
    setEditingAsset(null);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEdit = (record) => {
    setEditingAsset(record);
    form.setFieldsValue({
      assetId: record.assetId,
      assetName: record.assetName,
      depId: record.depId,
      totalNum: record.totalNum,
      assetNum: record.assetNum
    });
    setModalVisible(true);
  };

  const handleDelete = async (id) => {
    try {
      const response = await deleteAsset(id);
      console.log('删除资产响应:', response);
      
      const newList = await getAssetList();
      
      const assetStillExists = newList.data?.some(asset => asset.assetId === id);
      
      if (!assetStillExists) {
        message.success('删除成功');
        setAssets(newList.data || []);
      } else {
        message.error(response?.message || '删除失败');
        setAssets(newList.data || []);
      }
    } catch (error) {
      console.error('删除资产失败:', error);
      fetchAssets();
      message.error('操作异常，请刷新页面查看最新状态');
    }
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      if (editingAsset) {
        const response = await updateAsset(editingAsset.assetId, values);
        if (response && response.code === 200) {
          message.success('更新成功');
          setModalVisible(false);
          fetchAssets();
        } else {
          message.error(response?.message || '更新失败');
        }
      } else {
        const assetData = {
          ...values,
          assetNum: values.totalNum,
          assetStatus: '正常'
        };
        const response = await createAsset(assetData);
        if (response && response.code === 200) {
          message.success('创建成功');
          setModalVisible(false);
          fetchAssets();
        } else {
          message.error(response?.message || '创建失败');
        }
      }
    } catch (error) {
      console.error('操作失败:', error);
      message.error('操作失败，请检查输入数据');
    }
  };

  const columns = [
    {
      title: '资产ID',
      dataIndex: 'assetId',
      key: 'assetId',
    },
    {
      title: '资产名称',
      dataIndex: 'assetName',
      key: 'assetName',
    },
    {
      title: '状态',
      dataIndex: 'assetStatus',
      key: 'assetStatus',
    },
    {
      title: '所属部门',
      dataIndex: 'depId',
      key: 'depId',
      render: (depId) => departments.find(d => d.depId === depId)?.depName || depId,
    },
    {
      title: '当前数量',
      dataIndex: 'assetNum',
      key: 'assetNum',
    },
    {
      title: '总数量',
      dataIndex: 'totalNum',
      key: 'totalNum',
    },
    user?.admin === 'yes' && {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Button
            type="primary"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.assetId)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ].filter(Boolean);

  return (
    <div style={{ position: 'relative', minHeight: '100vh', padding: '20px' }}>
      <div style={{
        position: 'fixed',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        backgroundImage: 'url(/assets/flowers.jpg)',
        backgroundSize: 'cover',
        backgroundPosition: 'center',
        backgroundRepeat: 'no-repeat',
        opacity: 0.8,
        zIndex: 0,
        pointerEvents: 'none'
      }} />

      <div style={{ 
        position: 'relative', 
        zIndex: 1,
        background: 'rgba(255, 255, 255, 0.9)',
        padding: '24px',
        borderRadius: '12px',
        boxShadow: '0 2px 12px rgba(0,0,0,0.1)'
      }}>
        <div style={{ 
          display: 'flex', 
          justifyContent: 'space-between', 
          alignItems: 'center',
          marginBottom: '24px'
        }}>
          <h2 style={{ margin: 0 }}>资产管理</h2>
          {user?.admin === 'yes' && (
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={handleAdd}
            >
              添加资产
            </Button>
          )}
        </div>

        <Table
          columns={columns}
          dataSource={assets}
          loading={loading}
          pagination={{
            total: assets.length,
            pageSize: 10,
            showTotal: (total) => `共 ${total} 条记录`,
            showSizeChanger: true,
            showQuickJumper: true
          }}
          style={{ 
            background: 'white',
            borderRadius: '8px',
            overflow: 'hidden'
          }}
        />
      </div>

      <Modal
        title={editingAsset ? '编辑资产' : '添加资产'}
        open={modalVisible}
        onOk={handleSubmit}
        onCancel={() => setModalVisible(false)}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="assetId"
            label="资产ID"
            rules={[{ required: true, message: '请输入资产ID' }]}
          >
            <Input disabled={!!editingAsset} />
          </Form.Item>
          <Form.Item
            name="assetName"
            label="资产名称"
            rules={[{ required: true, message: '请输入资产名称' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="depId"
            label="所属部门"
            rules={[{ required: true, message: '请选择所属部门' }]}
          >
            <Select>
              {departments.map(dept => (
                <Select.Option key={dept.depId} value={dept.depId}>
                  {dept.depName}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="totalNum"
            label="总数量"
            rules={[{ required: true, message: '请输入总数量' }]}
          >
            <Input type="number" min={0} />
          </Form.Item>
          {editingAsset && (
            <Form.Item
              name="assetNum"
              label="当前数量"
              rules={[
                { required: true, message: '请输入当前数量' },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue('totalNum') >= value) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('当前数量不能大于总数量'));
                  },
                }),
              ]}
            >
              <Input type="number" min={0} />
            </Form.Item>
          )}
        </Form>
      </Modal>
    </div>
  );
};

export default AssetList; 